package im.ok.back.util.excel;

import cn.hutool.core.lang.UUID;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import im.ok.back.dao.FeedBackMapper;
import im.ok.back.pojo.FeedBack;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class FeedbackExcelListener extends AnalysisEventListener<FeedbackDTO> {

    List<FeedbackDTO> list = new ArrayList<>();

    private FeedBackMapper feedBackMapper;

    public FeedbackExcelListener(FeedBackMapper feedBackMapper) {
        this.feedBackMapper = feedBackMapper;
    }


    @Override
    public void invoke(FeedbackDTO feedbackDTO, AnalysisContext analysisContext) {
        log.info("解析到一条记录：{}", feedbackDTO);
        list.add(feedbackDTO);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        savaData();
    }

    private void  savaData() {
        log.info("{}条数据开始入库！", list.size());
        List<FeedBack> feedBackList = new ArrayList<>();
        for (FeedbackDTO feedbackDTO : list) {
            FeedBack feedBack = new FeedBack();
            BeanUtils.copyProperties(feedbackDTO, feedBack);
            feedBack.setId(UUID.randomUUID().toString(true));
            feedBackList.add(feedBack);
        }
        feedBackMapper.insertBatch(feedBackList);
        log.info("入库成功！");
    }
}
